﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class CustomerManagement_PresentCouponDetail : System.Web.UI.Page
{
    TextBox txtNote;

    private bool IsAudit
    {
        get
        {
            bool isAudit = false;
            if (ViewState["IsAudit"] != null)
            {
                isAudit = Convert.ToBoolean(ViewState["IsAudit"]);
            }
            return isAudit;
        }
        set
        {
            ViewState["IsAudit"] = value;
        }
    }

    private DataTable PresentCouponList
    {
        get
        {
            DataTable presentCouponList = null;
            if (ViewState["PresentCouponList"] != null)
            {
                presentCouponList = (DataTable)ViewState["PresentCouponList"];
            }
            
            return presentCouponList;
        }
        set
        {
            ViewState["PresentCouponList"] = value;
        }
    }

    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("300400111");
        if (!IsPostBack)
        {
            BindMain();
            BindDetails();
            if (this.IsAudit)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                pnl.Enabled = false;
            }
            btnCancel.Attributes.Add("onclick", "if(!confirm('要取消吗?'))return false;");
            btnReturn.Attributes.Add("onclick", "if(!confirm('要返回吗?'))return false;");
            btnDelete.Attributes.Add("onclick", "if(!confirm('要删除吗?'))return false;");
        }
    }

    private void BindMain()
    {

        DataSet dst = new BLL.PresentCouponMain().GetMainById(this.Code);
        if (dst.Tables[0].Rows.Count > 0)
        {
            this.IsAudit = dst.Tables[0].Rows[0]["pc_CHECK"].ToString() == "1" ? true : false;
        }
        dlistMain.DataSource = dst;
        dlistMain.DataBind();

        if (this.IsAudit)
        {
            dlistMain.Enabled = false;
        }
    }

    private void BindDetails()
    {
        this.PresentCouponList = new BLL.PresentCouponDetail().GetDetailsById(this.Code);
        dlistPresentCoupon.DataSource = this.PresentCouponList;
        dlistPresentCoupon.DataBind();
        if (this.IsAudit)
        {
            dlistPresentCoupon.Enabled = false;
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (hidCustomer.Value == "")
        {
            Share.Alert(this.Page, "请选择会员！");
            return;
        }
        if (hidCoupon.Value == "")
        {
            Share.Alert(this.Page, "请选择礼券！");
            return;
        }
        char[] ch = new char[] { '$' };
        string[] arrCouponSelectedResult = hidCoupon.Value.TrimEnd(ch).Split('$');
        string[] arrCustomerSelectedResult = hidCustomer.Value.Split('|');
        string[] arrTemp;
        for (int i = 0; i < arrCouponSelectedResult.Length; i++)
        {
            arrTemp = arrCouponSelectedResult[i].Split('|');
            if (ValidCouponCodeIsSelected(arrTemp[0]))
            {
                continue;
            }
            new BLL.PresentCouponDetail().AddDataRowToDataTable(this.PresentCouponList, arrCustomerSelectedResult[0], arrCustomerSelectedResult[1], arrTemp[0], Convert.ToDecimal(arrTemp[1]));
        }

        dlistPresentCoupon.DataSource = this.PresentCouponList;
        dlistPresentCoupon.DataBind();

        hidCoupon.Value = "";
        hidCustomer.Value = "";
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400111", "00017"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.PresentCouponMain pcm = new BLL.PresentCouponMain().GetModel(this.Code);
            if (pcm != null)
            {
                if (pcm.PC_Check==1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            if (this.PresentCouponList.Rows.Count == 0)
            {
                throw new Exception("请添加要赠送给客户的礼券！");
            }
            if (new BLL.PresentCouponMain().Save(this.Code, this.PresentCouponList, ((TextBox)dlistMain.Items[0].FindControl("txtNote")).Text))
            {
                Share.InsertLog("300400111", "00017");
                Share.Alert(this.Page, "保存成功！");
            }
            else
            {
                Share.Alert(this.Page, "保存失败，请重新尝试保存！");
            }

        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400111", "00010"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.PresentCouponMain pcm = new BLL.PresentCouponMain().GetModel(this.Code);
            if (pcm != null)
            {
                if (pcm.PC_Check == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            this.PresentCouponList = new BLL.PresentCouponDetail().GetDetailsById(this.Code);
            StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
            StringBuilder strSqlToUpdateErpDB = new StringBuilder();
            char[] charToTrim = new char[] { '|' };
            string strCommandOfBStyle;
            string strCommandOfErp;
            string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
            string[] strArraySqlCommandArrayToUpdateBStyleDB;
            string[] strArraySqlCommandArrayToUpdateErpDB;
            string user = Share.UserValue(0);

            for (int i = 0; i < dlistMain.Items.Count; i++)
            {
                txtNote = (TextBox)dlistMain.Items[i].FindControl("txtNote");
            }

            strSqlToUpdateBStyleDB.Append("update PresentCouponMain set PC_Check=1,PC_Checker='");
            strSqlToUpdateBStyleDB.Append(user);
            strSqlToUpdateBStyleDB.Append("',PC_CheckDate='");
            strSqlToUpdateBStyleDB.Append(DateTime.Now);
            strSqlToUpdateBStyleDB.Append("' where PC_ID='");
            strSqlToUpdateBStyleDB.Append(this.Code);
            strSqlToUpdateBStyleDB.Append("'|");

            for (int i = 0; i < this.PresentCouponList.Rows.Count; i++)
            {
                strSqlToUpdateBStyleDB.Append("insert into LIQUAN_CUSTOMER(CouponCode,CustomerCode,Amount,OrderCode,Active,ActiveDate,Frozen) values('");
                strSqlToUpdateBStyleDB.Append(this.PresentCouponList.Rows[i]["CouponCode"].ToString());
                strSqlToUpdateBStyleDB.Append("','");
                strSqlToUpdateBStyleDB.Append(this.PresentCouponList.Rows[i]["CustomerCode"].ToString());
                strSqlToUpdateBStyleDB.Append("',");
                strSqlToUpdateBStyleDB.Append(this.PresentCouponList.Rows[i]["CouponAmount"].ToString());
                strSqlToUpdateBStyleDB.Append(",'',1,'");
                strSqlToUpdateBStyleDB.Append(DateTime.Now);
                strSqlToUpdateBStyleDB.Append("',0)|");

                strSqlToUpdateBStyleDB.Append("update czkzcdmx set state=3 where CZKBH='");
                strSqlToUpdateBStyleDB.Append(this.PresentCouponList.Rows[i]["CouponCode"].ToString());
                strSqlToUpdateBStyleDB.Append("'|");

                strSqlToUpdateErpDB.Append("update czkzcdmx set state=3 where CZKBH='");
                strSqlToUpdateErpDB.Append(this.PresentCouponList.Rows[i]["CouponCode"].ToString());
                strSqlToUpdateErpDB.Append("'|");
            }
            
            strCommandOfBStyle = strSqlToUpdateBStyleDB.ToString();
            strCommandOfErp = strSqlToUpdateErpDB.ToString();

            strArraySqlCommandArrayToUpdateBStyleDB = strCommandOfBStyle.TrimEnd(charToTrim).Split(charToTrim);
            strArraySqlCommandArrayToUpdateErpDB = strCommandOfErp.TrimEnd(charToTrim).Split(charToTrim);

            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();

            bool result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, strArraySqlCommandArrayToUpdateBStyleDB, strArraySqlCommandArrayToUpdateErpDB);
            if (result)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                pnl.Enabled = false;
                BindMain();
                BindDetails();

                Share.InsertLog("300400111", "00010");
                Share.Alert(this.Page, "审核成功！");
            }
            else
            {
                Share.Alert(this.Page, "审核失败，请重新审核！");
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400111", "00003"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.PresentCouponMain pcm = new BLL.PresentCouponMain().GetModel(this.Code);
            if (pcm != null)
            {
                if (pcm.PC_Check == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("delete from PresentCouponMain where pc_id='");
            sbSql.Append(this.Code);
            sbSql.Append("'|");

            sbSql.Append("delete from PresentCouponDetail where PC_MainId='");
            sbSql.Append(this.Code);
            sbSql.Append("'|");

            string stringSql = sbSql.ToString();
            char[] charToTrim = new char[] { '|' };
            string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);

            if (new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray))
            {
                Share.InsertLog("300400111", "00003");
                Response.Write("<script>alert('删除成功！');window.location.href='PresentCouponMain.aspx'</script>");
            }
            else
            {
                Response.Write("<script>alert('删除失败！');</script>");
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("PresentCouponDetail.aspx?code=" + this.Code);
    }

    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("PresentCouponMain.aspx");
    }

    protected void dlistPresentCoupon_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "del")
        {
            this.PresentCouponList.Rows.RemoveAt(e.Item.ItemIndex);
            dlistPresentCoupon.DataSource = this.PresentCouponList;
            dlistPresentCoupon.DataBind();
        }
    }

    /// <summary>
    /// 检查礼券编号是否已经被分配给客户
    /// </summary>
    /// <param name="couponCode"></param>
    /// <returns></returns>
    private bool ValidCouponCodeIsSelected(string couponCode)
    {
        bool result = false;
        for (int j = 0; j < this.PresentCouponList.Rows.Count; j++)
        {
            if (this.PresentCouponList.Rows[j]["couponcode"].ToString() == couponCode)
            {
                result = true;
                break;
            }
        }
        return result;
    }
}
